import {deepFullCopy, messages, queryCurrencyPrecision} from "share/common";
import React  from 'react'
import { connect } from 'react-redux'
import {Button, Row, Col, Form, message, InputNumber, Icon, Popconfirm} from 'antd'
import 'styles/my-account/components/expense-amortise.scss'

import ResizeTable from "components/resize-table";
import expenseReportService from "../../expense-report/expense-report.service";
import Selector from "components/selector";
import Annotate from "components/template/annotate";


class MyAccount extends React.Component{

  state = {
    columns: [{
      title:  messages('common.sequence')/*序号*/,
      dataIndex: 'index',
      width: 64,
      render: (value, record, index) => <span>{index + 1}</span>
    }, {
      title:  messages('expense-1.key55')/*摊销期间*/,
      dataIndex: 'periodId',
      render: (value, record, index) => this.props.disabled ? record.periodName : (
        <Selector
          value={value ? {id: record.periodId, periodName: record.periodName} : null}
          type="accounting_period"
          params={{ setOfBooksId: this.props.company.setOfBooksId }}
          onChange={periodObj => this.onChangePeriodSeq(periodObj, index)}
          showSearch
          entity
          placeholder={messages('expense-1.key56')/*请输入temp2*/}
          getPopupContainer={() => document.body}
        />)
    }, {
      title: messages('expense-1.key57')/*摊销金额*/,
      dataIndex: 'amount',
      render: value => this.filterMoney(value, queryCurrencyPrecision(this.props.currencyCode))
    }, {
      title: messages('expense-1.key58')/*摊销比例*/,
      dataIndex: 'proportion',
      render: (value, record, index) => this.props.disabled ? this._precisionOverflow(Number(value) * 100, 2) + '%' : (
        <InputNumber
          className="amortise-proportion"
          onChange={(proportion) => this.onChangeProportion(proportion, index)}
          value={value * 100}
          max={100}
          min={0}
          precision={2}
          step={queryCurrencyPrecision(this.props.currencyCode) ? 1 / Math.pow(10, 2) : 1}
          formatter={value => (typeof value === 'number' && !isNaN(value)) ? Number(value.toFixed(2)) : value}
        />
      )
    }, ],
    value: [],
    accountingPeriod: [],
    startPeriod: null,
    endPeriod: null,
    selectedAccountingPeriod: []
  };

  componentWillMount() {
    const { disabled } = this.props;
    let { columns } = this.state;
    if ('value' in this.props) {
      const value = this.props.value;
      this.setState({ value });
    }
    if(!disabled && !columns.filter(i => i.dataIndex === 'operate').length) {
      columns.push({
        title: messages('common.operation')/*操作*/,
        dataIndex: 'operate',
        width: 100,
        render: (value, record, index) => (
          <Button onClick={() => this.onDeleteAmortise(index)} type='link' disabled={this.props.disabled}>
            {messages('common.delete')/*删除*/}
          </Button>
        )
      });
      this.setState({ columns });
    }
  }

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      const value = nextProps.value;
      this.setState({ value });
    }
    if((!isNaN(this.props.amount) && !isNaN(nextProps.amount)) && this.props.amount !== nextProps.amount) {
      this.onChangeAmount(nextProps.amount);
    }
    if((nextProps.currencyCode !== this.props.currencyCode) ||
      (nextProps.expenseTypeId !== this.props.expenseTypeId)
    ) {
      this.onChange([]);
      this.setState({ value: [] });
    }
  }

  _precisionOverflow = (amount, precision) => {
    let _precision = precision || queryCurrencyPrecision(this.props.currencyCode);
    return Number(Number(amount).toFixed(_precision))
  };

  onChange = currentValue => {
    const { value } = this.state;
    const onChange = this.props.onChange;
    onChange && onChange(currentValue || value);
  };

  onChangePeriodSeq = (periodObj, index) => {
    const { value } = this.state;
    let dataSource = deepFullCopy(value);
    if(periodObj) {
      dataSource[index].periodId = periodObj.id;
      dataSource[index].periodSeq = periodObj.periodSeq;
      dataSource[index].periodName = periodObj.periodName;
    } else {
      dataSource[index].periodId = null;
      dataSource[index].periodSeq = null;
    }
    this.setState({ value: dataSource }, this.onChange);
  };

  onChangeAmount = amount => {
    const { value } = this.state;
    let dataSource = deepFullCopy(value) || [];
    let length = value.length;
    if(length) {
      dataSource = dataSource.map(i => {
        i.amount =  this._precisionOverflow(Number(amount) * i.proportion);
        return i
      });
      dataSource[length - 1].amount = Number(amount) - dataSource.reduce((total, i, index) => total + (index < length - 1 ? Number(i.amount) : 0), 0);
      dataSource[length - 1].amount = this._precisionOverflow(dataSource[length - 1].amount);
      this.setState({ value: dataSource }, this.onChange);
    }
  };

  onChangeProportion = (proportion, index) => {
    if(typeof proportion === 'number' && !isNaN(proportion)) {
      const { value } = this.state;
      const { amount } = this.props;
      let dataSource = deepFullCopy(value);
      let proportionValue = Number((proportion / 100).toFixed(4));
      dataSource[index].proportion = proportionValue || 0;
      dataSource[index].amount = Number(amount) * (proportionValue || 0);
      this.setState({ value: dataSource }, this.onChange);
    }
  };

  onDeleteAmortise = index => {
    const { value } = this.state;
    let dataSource = deepFullCopy(value);
    dataSource.splice(index, 1);
    this.setState({ value: dataSource }, this.onChange);
  };

  handleInitAmortise = () => {
    const { startPeriod, endPeriod } = this.state;
    if(!startPeriod || !endPeriod) {
      message.error(messages('expense-1.key59')/*请选择摊销期间*/);
      return;
    }
    if(startPeriod.periodSeq > endPeriod.periodSeq) {
      message.error(messages('expense-1.key60')/*期间大小不合理*/);
      return;
    }
    const { company: { setOfBooksId } } = this.props;
    let params = {
      setOfBooksId,
      startPeriod: startPeriod.periodSeq,
      endPeriod: endPeriod.periodSeq
    };
    expenseReportService.getAccountingPeriod(params).then(res => {
      if(res.data && res.data.length) {
        this.setState({ value: res.data }, () => {
          this.handleSpreadAmortise(this.props.amount);
        });
      }
    });
  };

  handleAddAmortise = () => {
    const { value } = this.state;
    let dataSource = deepFullCopy(value);
    dataSource.push({
      periodId: '',
      periodSeq: '',
      amount: 0,
      proportion: 0,
      periodName: ''
    });
    this.setState({ value: dataSource }, this.onChange)
  };

  handleSpreadAmortise = amount => {
    const { value } = this.state;

    if(!value || !value.length) {
      message.error(messages('expense-1.key61')/*请先生成摊销*/);
      return;
    }
    let dataSource = [];
    let length = value.length;
    value.map(i => {
      dataSource.push({
        periodId: i.periodId || i.id,
        periodSeq: i.periodSeq,
        amount: this._precisionOverflow(Number(amount) / length),
        proportion: Math.round((1 / length) * 10000) / 100,
        periodName: i.periodName,
        amortiseOID: i.amortiseOID || null
      })
    });
    dataSource[length - 1].proportion = 100 - dataSource.reduce((total, i, index) => total + (index < length - 1 ? i.proportion : 0), 0);
    dataSource[length - 1].amount = Number(amount) - dataSource.reduce((total, i, index) => total + (index < length - 1 ? Number(i.amount) : 0), 0);
    dataSource = dataSource.map(i => {
      i.proportion = i.proportion / 100;
      i.proportion = Number(i.proportion.toFixed(4));
      i.amount = this._precisionOverflow(i.amount);
      return i
    });
    this.setState({ value: dataSource }, this.onChange);
  };

  render(){
    const { columns, value, startPeriod, endPeriod } = this.state;
    const { company: { setOfBooksId }, disabled, amount, nowExpense, annotateList,
      handleAnnotateChange, isWaitForAudit, erAmortiseEnabled } = this.props;
    return erAmortiseEnabled ? (
       <div className="expense-amortise">
        <Annotate
          params={{
            typeName: 'INVOICE',
            entityID: nowExpense && nowExpense.id,
            target: { type: 'amortise' }
          }}
          disabled={!isWaitForAudit}
          annotateList={annotateList}
          onChange={handleAnnotateChange}
        >
          {!disabled && amount ? (
            <Row style={{height: 80}}>
              <Col span={8}>
                <Form.Item label={messages('expense-1.key62')/*摊销期间从*/} >
                  <Selector
                    type="accounting_period"
                    value={startPeriod ? {id: startPeriod.id, periodName: startPeriod.periodName} : null}
                    params={{ setOfBooksId, endPeriod: endPeriod ? endPeriod.periodSeq : null }}
                    onChange={value => this.setState({ startPeriod: value })}
                    entity
                    placeholder={messages('expense-1.key56')/*请输入temp2*/}
                  />
                </Form.Item>
              </Col>
              <Col span={8} offset={1}>
                <Form.Item label={messages('expense-1.key63')/*摊销期间至*/} >
                  <Selector
                    type="accounting_period"
                    value={endPeriod ? {id: endPeriod.id, periodName: endPeriod.periodName} : null}
                    params={{ setOfBooksId, startPeriod: startPeriod ? startPeriod.periodSeq : null }}
                    onChange={value => this.setState({ endPeriod: value })}
                    entity
                    placeholder={messages('expense-1.key56')/*请输入temp2*/}
                  />
                </Form.Item>
              </Col>
              <Col span={4} offset={1}>
                {
                  value && value.length && (startPeriod && endPeriod) ? (
                    <Popconfirm
                      title={messages('expense-1.key64')/*该操作将初始化摊销期间数据，请确认是否继续*/}
                      onConfirm={this.handleInitAmortise}
                      okText={messages('common.ok')/*确定*/}
                      cancelText={messages('common.cancel')/*取消*/}
                    >
                      <Button type='primary' style={{marginTop: 32}}>{messages('expense-1.key65')/*生成摊销*/}</Button>
                    </Popconfirm>
                  ) : (
                    <Button type='primary' onClick={this.handleInitAmortise} style={{marginTop: 32}}>{messages('expense-1.key65')/*生成摊销*/}</Button>
                  )
                }
              </Col>
            </Row>
          ) : null}
          {(value && value.length) ? <ResizeTable
            showUtils
            tableName="expense-amortise-table"
            rowKey={(record, index) => '' + record.periodId + index}
            columns={columns}
            dataSource={value}
            size="middle"
            bordered
            pagination={false}
            onRef={ref => this.tableRef = ref}
          /> : null}
          {!disabled && amount ? (
            <Row style={{marginTop: 12}} gutter={8}>
              <Col span={12} >
                <Button type="dashed" style={{width: '100%', height: 32}} onClick={this.handleAddAmortise}>{messages('expense-1.key66')/*新建摊销*/}</Button>
              </Col>
              <Col span={12}>
                <Button type="dashed" style={{width: '100%', height: 32}} onClick={() => this.handleSpreadAmortise(amount)}>{messages('expense-1.key10')/*一键均摊*/}</Button>
              </Col>
            </Row>
          ) : null}
        </Annotate>
      </div>
    ) : null
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    options: state.login.options,
  }
}

export default connect(mapStateToProps)(MyAccount);
